"""
@name : articles
@author : FengZT_19
@projectname: aishuyou
"""
from flask import Blueprint, request
from flask_restful import Api, Resource
from sqlalchemy import or_

from libs.auth import login
from libs.error_code import UserException, ArticleException, BookCategoriesException
from libs.handler import default_error_handler
from libs.response import generate_response
from model import db
from model.articles import Articles
from model.booktypes import BookTypes
from model.users import Users

article_bp = Blueprint("article", __name__, url_prefix="/v1")
api = Api(article_bp)


class ArticlesView(Resource):
    def get(self, id):
        """
        根据文章标题或文章id查找文章
        :param id: 文章id
        :return: 文章id、文章标题、文章正文、作者id、阅读量、点赞、收藏、创建时间、修改时间
        """
        if id:
            print(id)
            articles = Articles.query.filter(or_(Articles.article_id.contains(id), Articles.title.contains(id))).all()
            print(articles)
            if articles:
                for article in articles:
                    # 更改时间输出格式：创建、修改时间
                    article.CreateAt = article.article_CreateAt.strftime("%Y-%m-%d %H:%M:%S")
                    article.UpdateAt = article.article_UpdateAt.strftime("%Y-%m-%d %H:%M:%S")
                    # 阅读量+1
                    article.pageviews = article.pageviews + 1
                    db.session.add(article)
                    db.session.commit()
                return generate_response(message="get article success",
                                         data=[article.to_json() for article in articles])
            else:
                # 文章不存在
                raise ArticleException

    @login
    def post(self):
        """
        新增文章
        输入：标题、正文、类别、分享书籍名字、作者id
        输出：标题、作者id
        :return: create article success
        """
        title = request.json.get("title")
        article_body = request.json.get("article_body")
        book_categories = request.json.get("book_categories")
        book_name = request.json.get("book_name")
        user_id = request.json.get("user_id")
        # 判断是否存在该用户
        if Users.query.get(user_id):
            # 创建文章
            article_info = Articles(title=title,
                                    article_body=article_body,
                                    book_categories=book_categories,
                                    book_name=book_name,
                                    user_id=user_id)
            # 存入数据库
            db.session.add(article_info)
            db.session.commit()
            return generate_response(message="create article success", data={"title": title, "user_id": user_id})
        else:
            raise UserException

    @login
    def put(self, id):
        """
        输入：文章标题、文章类别id、正文、书籍名字
        输出：文章标题、文章id、作者id
        :param id:文章id
        :return:
        """
        article = Articles.query.get(id)
        # 判断文章是否存在
        if article:
            article.title = request.json.get("title")
            article.article_body = request.json.get("article_body")
            book_id = request.json.get("book_id")
            article.book_name = request.json.get("book_name")
            # 查找是否存在该书籍类别
            query_book_id = BookTypes.query.get(book_id)
            print(query_book_id.book_categories)
            if query_book_id:
                article.book_categories = query_book_id.book_categories
                db.session.add(article)
                db.session.commit()
                return generate_response(message="update article success",
                                         data={"title": article.title, "article_id": article.article_id,
                                               "user_id": article.user_id})
            else:
                raise BookCategoriesException
        else:
            raise ArticleException

    @login
    def delete(self, id):
        """
        删除文章
        :param id: 文章id
        :return: 文章id、文章标题、作者id
        """
        article = Articles.query.get(id)
        if article:
            db.session.delete(article)
            db.session.commit()
            return generate_response(message="delete article success",
                                     data={"article_id": id, "title": article.title, "user_id": article.user_id})
        else:
            raise ArticleException


api.add_resource(ArticlesView, "/articles")
api.add_resource(ArticlesView, "/articles/<id>", endpoint="articlesviewapi")
api.handle_error = default_error_handler
